package com.evan.wj.service;
import com.evan.wj.dao.CharacterDAO;
import com.evan.wj.pojo.Book;
import com.evan.wj.pojo.Career;
import com.evan.wj.pojo.Category;
import com.evan.wj.pojo.Character;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.List;

@Service
public class CharacterService {
    @Autowired
    CharacterDAO characterDAO;
    @Autowired
    CareerService careerService;

    public List<Character> list() {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return characterDAO.findAll(sort);
    }

    public void addOrUpdate(Character character) {
        characterDAO.save(character);
    }

    public void deleteById(int id) {
        characterDAO.deleteById(id);
    }

    public List<Character> listByCareer(int cid) {
        Career career = careerService.get(cid);
        return characterDAO.findAllByCareer(career);
    }

    public List<Character> Search(String keywords) {
        return characterDAO.findAllByNameLikeOrEnglishNameLike('%' + keywords + '%', '%' + keywords + '%');
    }
    public List<Character> findByScreen(int cid[],int rare[]){
        List<Character> lb = characterDAO.findAll(new Specification<Character>() {
            public Predicate toPredicate(Root<Character> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                Predicate p = criteriaBuilder.conjunction().not();
                if (null != cid) {
                    Join<Career, Character> join = root.join("career", JoinType.LEFT);
                    for(int a:cid){

                        p = criteriaBuilder.or(p, criteriaBuilder.equal(join.get("id"), a));
                    }
                }
               if (null != rare)
                {
                    for(int a:rare){
                        p = criteriaBuilder.or(p, criteriaBuilder.equal(root.get("rare"), a));
                    }
                }
                return p;
            }
        });
        return lb;
    }
 }

